#!/usr/bin/python

# Modules
import os
import shlex
import subprocess
import logging
import threading
import time

# My Modules
import manageservers
import readconfig

# Global Varables
intNumberServers = int(readconfig.readConfig(option = "numberServers"))
serverDirectory = readconfig.readConfig(option = "serverDirectory")
program = readconfig.readConfig(option = "program")
serverArg1 = readconfig.readConfig(option = "serverArg1")
serverArg2 = readconfig.readConfig(option = "serverArg2")
serverArg3 = readconfig.readConfig(option = "serverArg3")

e = threading.Event()
t = None

def startServer(num, e):
    while True:
        e.wait()
        os.chdir(serverDirectory)
        prepStr = serverDirectory + program + " " + serverArg1 + str(num) + serverArg2 + str(num) + serverArg3
        resultStr = shlex.split(prepStr)
        target = subprocess.Popen(resultStr, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        logging.debug("Server #" + str(num) + " with PID: " + str(target.pid) + " is now on-line.")
        manageservers.storePid(num, target.pid)
        target.communicate()
    return True

def stopServer(num, e):
    logging.debug("calling stop()")
    os.kill(manageservers.serverPids[str(num)], 15)
    logging.debug("Killed Server " + str(num) + " with PID of " + str(manageservers.serverPids[str(num)]) + ".")

def resumeEvent(e): #??
    logging.debug("e.set() called.")
    e.set()

def startServerThread(num,e):
    t = threading.Thread(target=startServer, args=(num,e))
    t.start()
